package com.goodboys.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by CJ on 2018-05-20.
 */
public class JwtUtils {

    //判断是够是有效的token
    public static boolean isValid(String authHeader){
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer "))  return false;
            String token = authHeader.substring(7);
            Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //获取账户的id
    public static String getUserId(String token){
        token = token.substring(7);
        Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
        return  claims.getSubject();
    }

    public static void main(String[] args) {
        String token = "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzYzlhNWViMjExZWI0ODIyOWM2OGNiNjYwMzFhOTUxYiIsImF1ZCI6IjEzOTgyMWJmNWI4MjJkNDRlZTRjNTA2YzU0MGUxMDhlIiwiaWF0IjoxNTI2ODExNDkzfQ.zh0TD6qv2AfmN-gVpCSx0e55PQDGh6cBVQBTKtMeEHM";
        String userId = JwtUtils.getUserId(token);
    }

    public static  boolean isPermission(String id, HttpServletRequest request){
        String authHeader = request.getHeader("authorization");
        String userId = getUserId(authHeader);
        if(userId == null) return false;
        return userId.equals(id);
    }


}
